#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
  const int N_repeat = 100;
  const int MessageSize=10000000;
  int* message = (int*) malloc(MessageSize*sizeof(int));
  int i;
  double total_time=0;
  for(i=0;i<MessageSize;++i)
    message[i]=0;
  
  MPI_Init(NULL, NULL);    
  
  int rank;
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  int world_size;
  MPI_Comm_size(MPI_COMM_WORLD, &world_size);

  if (world_size != 2) {
    fprintf(stderr, "World size must be two for %s\n", argv[0]);
    MPI_Abort(MPI_COMM_WORLD, 1);
  }

  int partner_rank = (rank+1) % 2;
  
  while (message[0] < N_repeat) {
    printf("%d\n",message[0]);
    if (rank ==message[0] % 2) 
    {
      message[0]++;
      double t1 = MPI_Wtime();
      MPI_Send(message, MessageSize, MPI_INT, partner_rank, 0, MPI_COMM_WORLD);
      double t2=(MPI_Wtime()-t1);
      total_time+=t2;
      //printf("Node %d sent a message to %d\n",rank, partner_rank);
    } 
    else 
    {
      double t1 = MPI_Wtime();
      MPI_Recv(message, MessageSize, MPI_INT, partner_rank, 0, MPI_COMM_WORLD,
               MPI_STATUS_IGNORE);
      double t2=(MPI_Wtime()-t1);
      total_time+=t2;
      //printf("Node %d received message from %d\n",rank, partner_rank);
    }
  }
  
  MPI_Finalize();
  printf("\n%f\n ",total_time/N_repeat);
  free(message);
  return 0;
}
